<?php
/**
 * 爬虫，使用百度api抓取地图数据
 */
require './include/config.php';

$data = array("bounds"=>@$_GET["geo"],"keyword"=>@$_GET["industry"],"city"=>@$_GET["city"],"keyapi"=>@$_GET["key"],"page"=>@$_GET["page"],"pagesize"=>"20");
$url = "http://api.map.baidu.com/place/v2/search?bounds={#bounds}&query={#keyword}&region={#city}&output=json&ak={#keyapi}&page_size={#pagesize}&page_num={#page}";
$url = replaceAll($url,$data);
robootBaidu($url);
close_mysql();


function robootBaidu($url) {
    if (($output = cache($url)) == null) {
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_HEADER, 0);
    	$output = curl_exec($ch);
    	curl_close($ch);
    	// print_r($output);
    	$output = stripslashes($output);
    	$output = json_decode($output, true);
    	$output['url'] = $url;
    	cache($url, $output);
    }
    if(isset($_GET['debug'])) {
        header("content-type:text/plain;charset=utf8");
        $output['url'] = urldecode($output['url']);
        var_dump($output); 
        exit;
    }
    $die = true;
    $list = array();
	if (isset($output["message"]) && $output["message"] == "ok" && sizeof($output["results"]) > 0) {
        $die = false;
	    $time = time();
		foreach ($output["results"] as $i => $k) {
			@$data['b_name'] = $k["name"];
			@$data['b_lat'] = $k["location"]["lat"];
			@$data['b_lng'] = $k["location"]["lng"];
			@$data['b_address'] = $k["address"];
			@$data['b_street_id'] = $k["street_id"];
			@$data['b_telephone'] = $k["telephone"];
			@$data['b_uid'] = $k["uid"];
			@$data['b_city'] = $_GET["cityID"];
			@$data['b_industry'] = $_GET["industryID"];
			$data['b_utime'] = $time;
			$list[] = $data;
		}
		batchInsert($list, 'rb_business', true);
	}
	
	if (!isset($output["message"])) {
	    echo json_encode(array('status'=>'null', 'data' => $output));
	} elseif($output["status"]=='302') {
	    echo json_encode(array('status'=>'302', 'data' => $output));
	} elseif ($die) {
	    echo json_encode(array('status'=>'null'));
	} else {
	    echo json_encode(array('status'=>'ok', 'count'=>count($list)));
	}
}


